# Some change has been made by Vipin.

# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  helper :all # include all helpers, all the time

  # See ActionController::RequestForgeryProtection for details
  # Uncomment the :secret if you're not using the cookie session store
  protect_from_forgery # :secret => 'd0a4b4c93f809f9a7aa3b8e6545c27db'
    
  # before_filter :process_messages

  # See ActionController::Base for details 
  # Uncomment this to filter the contents of submitted sensitive data parameters
  # from your application log (in this case, all fields with names like "password"). 
  # filter_parameter_logging :password

  def process_messages
    
    # From Frontline SMS
    
    # Narrow down query to only latest messages - If no pings to compare to, then create a dummy ping   
    last_ping = Ping.find :last
    if last_ping.nil?
      ping = Ping.new(:content => "Database Restarted - Dummy Ping", :message => "Database Restarted - Dummy Ping")
      ping.created_at = Time.now+5.hours+30.minutes
      ping.updated_at = Time.now+5.hours+30.minutes
      ping.save!
      last_ping = Ping.find :last
    end
    
    # Pull new messages from FrontlineSMS and save as message part or ping depending on content
	  #new_messages = Message.find_by_sql "SELECT frontline_messages.tid FROM frontline_messages LEFT JOIN pings ON frontline_messages.tid=pings.tid WHERE frontline_messages.tid IS NOT NULL AND type = 1 AND status = 1 AND pings.tid IS NULL AND frontline_messages.tid <> 0 AND dateTimeP > "+last_ping.updated_at.strftime("'%m-%d-%Y %H:%M:%S'")
    
    last_message = Message.find(:last)
    last_sub = CrsForm.find(:last)
    if !last_sub.nil?
      since = last_sub.created_at + 5.hours + 30.minutes
    else
      since = last_ping.created_at
    end
        
    new_messages = Message.find_by_sql "SELECT frontline_messages.tid FROM frontline_messages WHERE dateTimeP > "+since.strftime("'%Y-%m-%d %H:%M:%S'")
    new_messages = Message.find new_messages
    new_messages.each do |message|
      begin
        if message.is_message_part?
          message.save_as_message_part
        else    
          message.save_as_ping
        end
      rescue
        message.status = 5
        message.save!
        flash[:notice] = "'"+message.content+"' could not be saved."
      end
    end
    
    # From Twitter:
    # 
    # begin
    #   last_ping = Ping.find :last, :conditions => ["twitter_username <> ''"]
    #   since = ""
    #   if last_ping.nil?
    #     last_part = MessageParts.find :last, :conditions => ["twitter_username <> ''"]
    #     if last_part.nil?
    #       since = Date.new(2009,01,01).strftime("%a%%2C+%d+%b+%Y+%H%%3A%M%%3A%S+GMT")
    #     else
    #       since = (last_part.created_at+1.second).strftime("%a%%2C+%d+%b+%Y+%H%%3A%M%%3A%S+GMT")
    #     end
    #   else
    #     since = (last_ping.created_at+1.second).strftime("%a%%2C+%d+%b+%Y+%H%%3A%M%%3A%S+GMT")
    #   end
    #   new_tweets = Tweet.find(:all, :from=>"/statuses/friends_timeline/crs_rapid.xml?since="+since)
    #   new_tweets.reverse.each do |tweet|
    #     if tweet.is_message_part?
    #       part = tweet.save_as_message_part
    #     else
    #       ping = tweet.save_as_ping
    #     end
    #   end
    # rescue
    #   flash[:notice] = "dropped connection from Twitter"
    # end
    # 

    # locate all unprocessed message parts and split by form ID
    unproccessed_parts = MessageParts.find_all_by_processed(false)
    grouped_by_phone = unproccessed_parts.group_by(&:phone_id)
    
    for user in grouped_by_phone.keys
      grouped_parts = grouped_by_phone[user].group_by(&:form_id)
      for id in grouped_parts.keys
        # In this case, we have all the message parts (get the total from the metadata in 1st message part)
        if grouped_parts[id].size >= grouped_parts[id][0].total_parts
          submission = CrsForm.new
        
          # Concatenate the payloads of the parts to form the full message payload
          sub_payload = ""
          for part in grouped_parts[id].sort! {|a,b| a.current_part <=> b.current_part}
            sub_payload = sub_payload + part.payload
          end
        
          crs_field_split = sub_payload.split("&")
          field_hash = {}
          for message in crs_field_split
            pair = message.split("=")
            field_hash[pair[0]] = pair[1]
          end
        
          # Enter Payload Data into Individual Fields
          submission.g1 = field_hash['g1'].to_i
          submission.g2 = field_hash['g2'].to_i
          submission.g3 = field_hash['g3'].to_i
          submission.g4 = field_hash['g4'].to_i
          submission.g5 = field_hash['g5'].to_i
          submission.g6 = field_hash['g6'].to_i
          submission.g7 = field_hash['g7'].to_i
          submission.g8 = field_hash['g8'].to_i
          submission.g9 = field_hash['g9'].to_i
          submission.ga = field_hash['ga'].to_i
        
          submission.d1 = field_hash['d1'].to_i
          submission.d2 = field_hash['d2'].to_i
          submission.d3 = field_hash['d3'].to_i
          submission.d4 = field_hash['d4'].to_i
          submission.d5 = field_hash['d5'].to_i
          submission.d6 = field_hash['d6'].to_i
          submission.d7 = field_hash['d7'].to_i
          submission.d8 = field_hash['d8'].to_i
          submission.d9 = field_hash['d9'].to_i
          submission.da = field_hash['da'].to_i
          submission.db = field_hash['db'].to_i
          submission.dc = field_hash['dc'].to_i
          submission.dd = field_hash['dd'].to_i
          submission.de = field_hash['de'].to_i
          submission.df = field_hash['df'].to_i
          submission.dg = field_hash['dg'].to_i
          submission.dh = field_hash['dh'].to_i
        
          submission.h1 = field_hash['h1'].to_i
          submission.h2 = field_hash['h2'].to_i
          submission.h3 = field_hash['h3']
          submission.h4 = field_hash['h4'].to_i
          submission.h5 = field_hash['h5'].to_i
          submission.h6 = field_hash['h6'].to_i
          submission.h7 = field_hash['h7'].to_i
          submission.h8 = field_hash['h8'].to_i
          submission.h9 = field_hash['h9'].to_i
          submission.ha = field_hash['ha'].to_i
          submission.hb = field_hash['hb'].to_i
          submission.hc = field_hash['hc'].to_i
        
          submission.i1 = field_hash['i1'].to_i
          submission.i2 = field_hash['i2'].to_i
          submission.i3 = field_hash['i3'].to_i
          submission.i4 = field_hash['i4']
          submission.i5 = field_hash['i5'].to_i
          submission.i6 = field_hash['i6'].to_i
          submission.i7 = field_hash['i7'].to_i
        
          submission.s1 = field_hash['s1'].to_i
          submission.s2 = field_hash['s2'].to_i
          submission.s3 = field_hash['s3'].to_i
          submission.s4 = field_hash['s4'].to_i
          submission.s5 = field_hash['s5'].to_i
          submission.s6 = field_hash['s6'].to_i
          submission.s7 = field_hash['s7'].to_i
          submission.s8 = field_hash['s8'].to_i
          submission.s9 = field_hash['s9'].to_i
          submission.sa = field_hash['sa'].to_i
          submission.sb = field_hash['sb'].to_i
          submission.sc = field_hash['sc'].to_i
          submission.sd = field_hash['sd'].to_i
          submission.se = field_hash['se'].to_i
          submission.sf = field_hash['sf'].to_i
        
          submission.w1 = field_hash['w1'].to_i
          submission.w2 = field_hash['w2'].to_i
          submission.w3 = field_hash['w3'].to_i
          submission.w4 = field_hash['w4']
          submission.w5 = field_hash['w5'].to_i
          submission.w6 = field_hash['w6'].to_i
          submission.w7 = field_hash['w7'].to_i
          submission.w8 = field_hash['w8'].to_i
          submission.w9 = field_hash['w9'].to_i
          submission.wa = field_hash['wa'].to_i
          submission.wb = field_hash['wb'].to_i
        
          submission.f1 = field_hash['f1'].to_i
          submission.f2 = field_hash['f2'].to_i
          submission.f3 = field_hash['f3'].to_i
        
          submission.r1 = field_hash['r1'].to_i
          submission.r2 = field_hash['r2'].to_i
          submission.r3 = field_hash['r3'].to_i
          submission.r4 = field_hash['r4'].to_i
          submission.r5 = field_hash['r5'].to_i
          submission.r6 = field_hash['r6'].to_i
          submission.r7 = field_hash['r7'].to_i
          submission.r8 = field_hash['r8'].to_i
          submission.r9 = field_hash['r9'].to_i
          submission.ra = field_hash['ra'].to_i
          submission.rb = field_hash['rb'].to_i
          submission.rc = field_hash['rc'].to_i
          submission.rd = field_hash['rd'].to_i
          submission.re = field_hash['re'].to_i
          submission.rf = field_hash['rf'].to_i
          submission.rg = field_hash['rg'].to_i
          submission.rh = field_hash['rh'].to_i
          submission.ri = field_hash['ri'].to_i
          submission.rj = field_hash['rj'].to_i
          submission.rk = field_hash['rk'].to_i
          submission.rl = field_hash['rl'].to_i
          submission.rm = field_hash['rm'].to_i
          submission.rn = field_hash['rn'].to_i
          submission.ro = field_hash['ro'].to_i
        
          submission.p1 = field_hash['p1'].to_i
          submission.p2 = field_hash['p2'].to_i
          submission.p3 = field_hash['p3'].to_i
        
          submission.x1 = field_hash['x1'].to_i
        
          # Geographic Data
          submission.address = grouped_parts[id][0].address
          submission.country = grouped_parts[id][0].country
          submission.state = grouped_parts[id][0].state
          submission.locality = grouped_parts[id][0].locality
          submission.street_number = grouped_parts[id][0].street_number
          submission.thoroughfare = grouped_parts[id][0].thoroughfare
          submission.postalcode = grouped_parts[id][0].postalcode
          submission.accuracy = grouped_parts[id][0].accuracy
          submission.latitude = grouped_parts[id][0].latitude
          submission.longitude = grouped_parts[id][0].longitude
    
          # Other Meta Data
          submission.phone_id = grouped_parts[id][0].phone_id
          submission.twitter_username = grouped_parts[id][0].twitter_username
          submission.ping_type = grouped_parts[id][0].ping_type   #  Fixme: Are these necessary?
          submission.tid = grouped_parts[id][0].tid               #
        
          submission.save!
        
          # Mark all parts in this message as processed so they will be ignored in the future
          # Todo: future functionality - we could possibly remove the parts from the database at this point in time
          for part in grouped_parts[id]
            part.processed = true
            part.save!
          end  
        end
        # Clear group parts?
      end
    end
    
  end

end

Mime::Type.register "text/kml", :kml

# module ActiveRecord
#   module ConnectionAdapters # :nodoc:
# 
#     module Quoting
#       
#       def quoted_true
#         "'true'"
#       end
# 
#       def quoted_false
#         "'false'"
#       end
# 
#     end
#   end
# end    